package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.transaction.UserTransaction;

import model.Apply;
import model.Mycomment;
import model.Myuser;
import model.Target;

import ejb.ApplyFacadeEJBRemote;
import ejb.CommentInspectRemote;
import ejb.TargetFacadeEJBRemote;
import ejb.UserFacadeEJBRemote;

/**
 * Servlet implementation class ReviewApply
 */
@WebServlet("/ReviewApply")
public class ReviewApply extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	@EJB UserFacadeEJBRemote uf;
	@EJB ApplyFacadeEJBRemote af;
	@EJB CommentInspectRemote ci;
	@EJB TargetFacadeEJBRemote tf;
    @PersistenceContext EntityManager em;
    @Resource private UserTransaction utx;
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ReviewApply() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		HttpSession session = request.getSession();
		String username = (String) session.getAttribute("username");
		
		String applyId = (String) request.getParameter("applyId");
		String review = (String) request.getParameter("review");
		String commentId = (String) request.getParameter("commentId");
		String targetId = (String) request.getParameter("targetId");
		
		try{
			if(username==null){
	            out.print("Please login first! redirecting to Login...");
	            response.setHeader("Refresh","2;URL=login.jsp");
			}
			else if(!(uf.findUserByName(username).getAuthority().equals("editor")||uf.findUserByName(username).getAuthority().equals("admin"))){
	            out.print("Oops, seems you do not have the authority to visit the editor page. Redirecting to Home page...");
	            response.setHeader("Refresh","2;URL=home.jsp");
			}
			else {					
				/* Review merchant application */
				if (applyId!=null && applyId!="" && review!=null && review!="" ){
					
					Apply app = af.getApplyById(Integer.valueOf(applyId.trim()));
					if (app!=null){
						boolean isApprove = false;
						if(review.equals("pass")){
							isApprove = true;							
						}else if(review.equals("deny")){
							isApprove = false;													
						}		
						
						Myuser user = app.getMyuser();
						Target target = app.getTargetBean();
						af.approveApplyById(app.getApplyid(), isApprove);
						
						utx.begin();
						
						// target has no merchant
						if(target.getMyuser() == null){
							if(user.getAuthority().equals("personal user")){
								user.setAuthority("merchant");
							}
						}
						else{
							List<Target> userTargetList = tf.getAllTargetsMerchantByOne(target.getMyuser());
							if(target.getMyuser().getAuthority().equals("merchant")){
								if(userTargetList.size()==1){
									target.getMyuser().setAuthority("personal user");
								}
								em.merge(target.getMyuser());
							}
							if(user.getAuthority().equals("personal user")){
								user.setAuthority("merchant");
							}
						}
						
						//user.setAuthority("merchant");						
						target.setMyuser(user);
						
						
						em.merge(user);						
						em.merge(target);						
						utx.commit();
						
					}		
					
				}else if(commentId!=null && commentId!=""){
					
					Mycomment comment = ci.getCommentById(Integer.valueOf(commentId.trim()));
					if (comment!=null){
						utx.begin();
						em.remove(em.merge(comment));
						utx.commit();
						
					}					
					
				}else if (targetId!=null && targetId!=""){
					Target target = tf.queryByTargetID(Integer.valueOf(targetId.trim()));					
					if (target!=null){
						target.setMchtinfo("");
						
						utx.begin();						
						em.merge(target);						
						utx.commit();
						
					}	
				}
				
							
				/* forward all the application to jsp */
				List<Apply> applyList = af.getAllWaitingApply();
				List<Mycomment> commentlist = ci.getAllComments();
				List<Target> targetlist = tf.getAllTargetWithMchtInfo();
				
		        request.setAttribute("applylist", applyList);		        
		        request.setAttribute("commentlist", commentlist);
		        request.setAttribute("targetlist", targetlist);
		        request.getRequestDispatcher("reviewapply.jsp").forward(request, response);
			
			}
		} catch (Exception e) {
			e.printStackTrace();				
	}
		
	}

}